package com.lzs.lzscodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.lzs.lzscodesandbox.model.ExecuteCodeRequest;
import com.lzs.lzscodesandbox.model.ExecuteCodeResponse;
import com.lzs.lzscodesandbox.model.ExecuteMessage;
import com.lzs.lzscodesandbox.model.JudgeInfo;
import com.lzs.lzscodesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.sql.ClientInfoStatus;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * Java代码原生沙箱
 */
@Slf4j
public class JavaCodeSandboxTemplate implements CodeSandbox {

    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    private static final long TIME_OUT = 5000L;

    /**
     * 1.用户代码保存为文件
     *
     * @param code 用户代码
     * @return
     */
    public File saveCodeFile(String code) {
        String userDir = System.getProperty("user.dir");// 获取到项目的根目录
        String globalCodePAthName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;// File.separator 用于匹配不同系统的 左（右）划线--> / \
        // 判断全局代码目录是否存在
        if (!FileUtil.exist(globalCodePAthName)) {
            FileUtil.mkdir(globalCodePAthName);// 不存在就新建
        }
        // 把用户代码隔离存放
        String userCodeParentPath = globalCodePAthName + File.separator + UUID.randomUUID();// 存放代码的文件夹目录
        // 实际代码文件Main.java
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        // 将用户代码写入文件
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
        return userCodeFile;
    }

    /**
     * 2.编译代码
     *
     * @param userCodeFile 用户代码保存的文件
     * @return
     */
    public ExecuteMessage compileFile(File userCodeFile) {
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());// 代码所在文件（Main.java）的路径
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);// 执行编译代码
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            if (executeMessage.getExitValue() != 0) {// 退出值
                throw new RuntimeException("编译错误");
            }
            return executeMessage;
        } catch (Exception e) {
//            return getErrorResponse(e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 3.执行代码，得到输出结果
     * @param userCodeFile 编译后的代码文件
     * @param inputList 输入参数列表
     * @return
     */
    public List<ExecuteMessage> runFile(File userCodeFile,List<String> inputList){// 编译后的代码文件,输入参数列表
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();// 父文件路径

        List<ExecuteMessage> executeMessagesList = new ArrayList<>();// 获取所有的输出结果信息列表
        for (String inputArgs : inputList) {
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, inputArgs);

            try {
                Process runProcess = Runtime.getRuntime().exec(runCmd);// Runtime.getRuntime()开启了新的子进程
                // 超时控制
                new Thread(() -> {
                    try {
                        Thread.sleep(TIME_OUT);// private static final long TIME_OUT = 5000L;
                        System.out.println("超时了，终端咯");
                        runProcess.destroy();// 睡醒还没执行完，杀死子进程
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }).start();
                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
//                ExecuteMessage executeMessage = ProcessUtils.runInteractProcessAndGetMessage(runProcess, inputArgs);
                System.out.println(executeMessage);
                executeMessagesList.add(executeMessage);// 将输出信息加入list
            } catch (Exception e) {
                throw new RuntimeException("执行错误：" + e);

            }
        }
        return executeMessagesList;
    }

    /**
     * 4.收集整理,获取输出结果
     * @param executeMessagesList
     * @return
     */
    public ExecuteCodeResponse getOutputResponse(List<ExecuteMessage>executeMessagesList){
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();// 获取结果集
        // 取最大值来判断是否超时
        long maxTime = 0;
        for (ExecuteMessage executeMessage : executeMessagesList) {
            String errorMessage = executeMessage.getErrorMessage();
            // 如果有错误信息
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                executeCodeResponse.setStatus(3);// 枚举值3-执行中存在错误
                break;
            }
            // 没有错误信息将输出集加入集合
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);// 原始值与新值比较哪个大
            }
        }
        if (outputList.size() == executeMessagesList.size()) {// 每一条信息都正常输出
            executeCodeResponse.setStatus(1);// 执行成功
        }
        // 将结果集放入响应对象
        executeCodeResponse.setOutputList(outputList);

        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
//        judgeInfo.setMemory(); 要借助第三方库获取执行内存
        executeCodeResponse.setJudgeInfo(judgeInfo);
        return executeCodeResponse;
    }

    /**
     * 5.删除文件
     * @param userCodeFile
     * @return
     */
    public boolean deleteFile(File userCodeFile) {
        if (userCodeFile.getParentFile() != null) {
            String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();// 父文件路径
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除：" + (del ? "成功" : "失败"));
            return del;
        }
        return true;
    }

    /**
     * 6.获取错误响应
     *
     * @param e
     * @return
     */
    // 创建方法，判断错误处理（错误处理前有内部异常处理）
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        // 表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        // 1.把用户代码保存成文件
        File userCodeFile = saveCodeFile(code);
        // 2.编译代码，得到class文件
        ExecuteMessage compileFileExecuteMessage = compileFile(userCodeFile);
        System.out.println(compileFileExecuteMessage);
        // 3.执行代码，得到输出结果
        List<ExecuteMessage> executeMessages = runFile(userCodeFile, inputList);
        // 4.收集整理输出结果
        ExecuteCodeResponse outputResponse = getOutputResponse(executeMessages);
        // 5.文件清理
        boolean b = deleteFile(userCodeFile);
        if (!b){
            log.error("deleteFile error,userCodeFilePath = {}",userCodeFile.getAbsolutePath());
        }
        return outputResponse;

    }



}
